import axios, {AxiosRequestConfig} from 'axios'
import {Toast} from "vant";
import {useUsersStore} from "../store/userInfo.ts";
import {useRouter} from "vue-router";
const router = useRouter()
// @ts-ignore
import {ElMessage} from "element-plus";
// 设置请求头和请求路径
axios.defaults.baseURL = import.meta.env.VITE_HTTP
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use(
    (config): AxiosRequestConfig<any> => {
        const store = useUsersStore();
        const token =  store.token
        if (token) {
            config.headers!.token = `${token}`
        }
        return config
    },
    (error) => {
        return error
    }
)

// 响应拦截
axios.interceptors.response.use((res) => {
    if (res.data.code == 8333){
        ElMessage.error("获取用户信息失败,请重新登陆")
        window.location.href ="/"
    }
    if (res.data.code === "200" || res.status == 200) {
        return res
    } else if (res.data.code === "500") {
        Toast.fail(res.data.msg);
    }
})

const handleResultDispose = (data: any, isShowMessage?: boolean) => {
    const result = data;
    if (!result) return undefined;
    if (result.code === '200') {
        if (isShowMessage && result.msg) {
            Toast.success(result.msg);
        }
        if (result.data) {
            return result.data;
        }
        return {};
    }
    if (result.code === '500' || result.code !== '200') {
        if (isShowMessage && result.msg) {
            Toast.fail(result.msg);
        }
    }
    return undefined;
};
interface ResType<T> {
    code: number
    data?: T
    msg: string
    err?: string
}
// @ts-ignore
interface Http {
    get<T>(url: string, params?: unknown, isShowMessage ?: boolean): Promise<ResType<T>>

    post<T>(url: string, params?: unknown, isShowMessage ?: boolean): Promise<ResType<T>>

    upload<T>(url: string, params: unknown): Promise<ResType<T>>

    download(url: string): void
}

const http: {
    // @ts-ignore
    download(url): void;
    // @ts-ignore
    post(url, params, isShowMessage?: boolean): Promise<unknown>;
    // @ts-ignore
    upload(url, file): Promise<unknown>;
    // @ts-ignore
    get(url, params, isShowMessage?: boolean): Promise<unknown>
} = {
    get(url, params, isShowMessage?: boolean) {
        return new Promise((resolve, reject) => {
            axios
                .get(url, {params})
                .then((res) => {
                    handleResultDispose(res.data, isShowMessage);
                    resolve(res.data)
                })
                .catch((err) => {
                    reject(err.data)
                })
        })
    },
    post(url, params, isShowMessage ?: boolean) {
        return new Promise((resolve, reject) => {
            axios
                .post(url, JSON.stringify(params))
                .then((res) => {
                    handleResultDispose(res.data, isShowMessage);
                    resolve(res.data)
                })
                .catch((err) => {
                    reject(err.data)
                })
        })
    },
    upload(url, file) {
        return new Promise((resolve, reject) => {
            axios
                .post(url, file, {
                    headers: {'Content-Type': 'multipart/form-data'},
                })
                .then((res) => {
                    resolve(res.data)
                })
                .catch((err) => {
                    reject(err.data)
                })
        })
    },
    download(url) {
        const iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = url
        iframe.onload = function () {
            document.body.removeChild(iframe)
        }
        document.body.appendChild(iframe)
    },

}
export default http
